package com.xuecheng.orders.application.service.impl;

import com.alipay.api.internal.util.AlipaySignature;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.orders.application.service.XcOrderApplication;
import com.xuecheng.orders.domain.model.vo.req.OrderCreateCmd;
import com.xuecheng.orders.domain.model.vo.resp.PayRecordResp;
import com.xuecheng.orders.domain.service.XcOrdersService;
import com.xuecheng.orders.infrastructure.config.AlipayConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static com.xuecheng.orders.infrastructure.config.AlipayConfig.ALIPAY_PUBLIC_KEY;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-09-12  22:32
 */
@Slf4j
@Service
public class XcOrderApplicationImpl implements XcOrderApplication {

    @Autowired
    private XcOrdersService xcOrdersService;

    @Value("${alipay.alipayPublicKey}")
    private String alipayPublicKey;

    @Override
    public PayRecordResp createOrder(Long userId, OrderCreateCmd orderCreateCmd) {
        if (Objects.isNull(orderCreateCmd) || Objects.isNull(userId)){
            throw new XueChengPlusException("参数不能为空");
        }

        return xcOrdersService.createOrder(userId, orderCreateCmd);
    }

    @Override
    public String requestPay(String payNo) {
        if (Objects.isNull(payNo)) {
            throw new XueChengPlusException("参数不能为空");
        }

        return xcOrdersService.requestPay(payNo);
    }

    @Override
    public void receivenotify(Map<String, String[]> parameterMap) {
        if (Objects.isNull(parameterMap) || parameterMap.isEmpty()){
            throw new XueChengPlusException("参数有误");
        }
        Map<String, String> params = getRequestParam(parameterMap);
        checkParamValid(params);

        xcOrdersService.receivenotify(params);
    }

    private void checkParamValid(Map<String, String> params) {
        // 验签
        try {
            boolean res = AlipaySignature.rsaCheckV1(params, alipayPublicKey, AlipayConfig.CHARSET, "RSA2");
            if (!res){
                throw new XueChengPlusException("验签失败");
            }
        } catch (Exception e){
            log.error("验签失败,{}", e.getMessage());
            throw new XueChengPlusException("验签失败");
        }
    }

    private Map<String, String> getRequestParam(Map<String, String[]> parameterMap) {
        Map<String, String> params = new HashMap<>();
        for (String s : parameterMap.keySet()) {
            String[] values = parameterMap.get(s);
            String str = "";
            for(int i = 0; i < values.length; i++){
                str = (i == values.length - 1) ? str + values[i] : str + values[i] + ",";
            }
            params.put(s, str);
            System.out.println(s + ":" + str);
        }

        return params;
    }
}
